package name.marz.to.go.ahg;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.logging.Logger;

import name.marz.to.go.ahg.SMBCVisa.SMBCVisaClient;
import name.marz.to.go.ahg.SMBCVisa.exception.BillPendingException;
import name.marz.to.go.ahg.SMBCVisa.executer.SMBCVisaLoginExecuter;
import name.marz.to.go.ahg.common.cli.OutDirOption;
import name.marz.to.go.ahg.common.cli.PasswordOption;
import name.marz.to.go.ahg.common.util.HttpUtil;
import name.marz.to.go.ahg.core.AbstractAutoGetterMain;
import name.marz.to.go.ahg.core.exception.UserProcessException;
import name.marz.to.go.ahg.core.executer.AbstractLoginExecuter;
import name.marz.to.go.ahg.core.executer.DocumentGetExecuter;
import name.marz.to.go.ahg.core.executer.FileDownloadExecuter;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.http.client.ClientProtocolException;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;


public class SMBCVisaGetMain extends AbstractAutoGetterMain {
	private static final Logger log = Logger.getLogger(SMBCVisaGetMain.class.getName());
	private final SMBCVisaClient client = new SMBCVisaClient();
	
	private String userId;
	private String password;
	private File outDir;

	/**
	 * 
	 */
	public SMBCVisaGetMain() {
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SMBCVisaGetMain main = new SMBCVisaGetMain();
		main.Main(args);
	}

	@Override
	public Document goTopPage() throws ClientProtocolException, IOException,
			UserProcessException {
		final String host = "https://www.smbc-card.com";
		DocumentGetExecuter executer = new DocumentGetExecuter(host+"/mem/top/index.jsp" ,client);
		return executer.execute();
	}

	@Override
	public Document doLogin(Document doc) throws ClientProtocolException,IOException, UserProcessException {
		final URI uri = HttpUtil.createURISafety("https://www.smbc-card.com/vp/xt_login.do?strURL=https%3A%2F%2Fwww%2Esmbc-card%2Ecom%2Fmem%2Ftop%2Findex%2Ejsp");
		AbstractLoginExecuter executer = new SMBCVisaLoginExecuter(uri, client,new String[] {userId},password);
		return executer.execute();
	}

	@Override
	public Document goDownloadPage(Document doc)
			throws ClientProtocolException, IOException, UserProcessException {
		final String host = "https://www.smbc-card.com/";
		// 口座の詳細ページへのURLを取得
		final String ANCHOR_GET_STR = "カードご利用状況"; 
		Elements elems = doc.getElementsContainingOwnText(ANCHOR_GET_STR);
		if ( elems.size() == 0 ) throw new IllegalStateException(ANCHOR_GET_STR+"が見つかりません");
		Element card_use_tbl = elems.first().parent().parent().parent().parent();
//		log.fine("カード利用状況ソース "+ card_use_tbl);
		Element pay_amount_tbl = card_use_tbl.getElementsByTag("tr").get(1)
									.getElementsByTag("table").first();
		log.fine("支払い金額ソース "+ pay_amount_tbl);
		Element pay_amount_row = pay_amount_tbl.getElementsByTag("tr").get(1);
		log.fine("支払い金額 行 ソース "+ pay_amount_row);
		// 請求未確定なら、取得しない
		if ( !pay_amount_row.html().contains("請求確定額") ) {
			throw new BillPendingException("請求が未確定です。明細書をダウンロードせず、中断します");
		}
		Element pay_amount_anchor = pay_amount_tbl.getElementsByTag("tr").get(1)
									.getElementsByTag("a").first();
		log.fine("当月支払分の明細へのアンカー "+pay_amount_anchor);
		String href = null;
		href = pay_amount_anchor.attr("href");
		final URI uri = HttpUtil.createURISafety(host,href);
		DocumentGetExecuter executer = new DocumentGetExecuter(uri, client);
		return executer.execute();
	}

	@Override
	public File doDownload(Document doc) throws ClientProtocolException,
			IOException, UserProcessException {
		final String host = "https://www.smbc-card.com/";
		// CSVダウンロードのURLを取得
		Elements elems = doc.getElementsContainingOwnText("CSV形式で保存");
		if ( elems.size() == 0 ) throw new IllegalStateException("CSVダウンロードURLが見つかりません");
		Element dl_anchor = elems.first();
		log.fine("CSV DLへのアンカー "+dl_anchor);
		final URI uri = HttpUtil.createURISafety(host, dl_anchor.attr("href"));
		FileDownloadExecuter executer = new FileDownloadExecuter(uri, client, outDir);
		return executer.execute();
	}

	@Override
	public void doLogout(Document doc) throws ClientProtocolException,
			IOException, UserProcessException {
		final String host = "https://www.smbc-card.com";
		DocumentGetExecuter executer = new DocumentGetExecuter(host+"/vp/xt_logout.do" ,client);
		executer.execute();
	}

	/* (non-Javadoc)
	 * @see name.marz.to.go.ahg.core.AbstractMain#finish()
	 */
	@Override
	protected void finish() {
		super.finish();
		// 終了処理
		client.getConnectionManager().shutdown();
	}
	
	@SuppressWarnings("static-access")
	@Override
	protected Options getOptions() {
		Options options = new Options();
		Option out = new OutDirOption(false);options.addOption(out);
		options.addOption(OptionBuilder.hasArg(true).withArgName("userid")
				.isRequired(true).withDescription("ID")
				.create("userid"));
		Option password = new PasswordOption(true); options.addOption(password);
		return options;
	}

	@Override
	protected void setParams(CommandLine cmd) {
		userId = cmd.getOptionValue("userid");
		this.password = cmd.getOptionValue(PasswordOption.OPT);
		outDir = new File(cmd.getOptionValue(OutDirOption.OPT, "."));
	}
}
